<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="站位编码" prop="stationCode">
        <el-input
          v-model="queryParams.stationCode"
          placeholder="请输入站位编码"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 80px;"
        />
      </el-form-item>
      <el-form-item label="产品编码" prop="partNumber">
        <el-input
          v-model="queryParams.partNumber"
          placeholder="请输入产品编码"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 400px;"
        />
      </el-form-item>
           
      <el-form-item label="总装线" prop="modelCode">
        <el-select v-model="queryParams.modelCode" placeholder="请选择生产总装线" clearable>
          <el-option
            v-for="dict in dict.type.product_line"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="生产时间">
        <el-date-picker v-model="dateRange" style="width: 300px" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="生产结果" prop="testResult">
        <el-select v-model="queryParams.testResult" placeholder="请选择生产结果" clearable>
          <el-option
            v-for="dict in dict.type.node_test_result"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>      
      <el-form-item label="数据状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择数据状态" clearable>
          <el-option
            v-for="dict in dict.type.node_result_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['order:result:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="resultList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标识" align="center" prop="id"  width="100"/>
      <el-table-column label="总装线" align="center" prop="modelCode" />
      <el-table-column label="站位编码" align="center" prop="stationCode" width="80"/>
      <el-table-column label="产品条码" align="center" prop="partNumber" />
      <el-table-column label="订单号" align="center" prop="orderNo" />
      <el-table-column label="生产内容" align="center" prop="testDetail" show-overflow-tooltip="normal"/>
      <el-table-column label="生产结果" align="center" prop="testResult" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.node_test_result" :value="scope.row.testResult"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.node_result_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="生成时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleOperateView(scope.row)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看生产内容详情对话框 -->
    <el-dialog :title="'生产内容详情'" :visible.sync="detailOpen" width="80%" append-to-body>
      <!-- 使用动态详情渲染组件 -->
      <DynamicDetailRenderer
        :data="currentTestDetail"
        :data-type="detectedDataType"
        :fields-per-row="3"
        :enable-grouping="true"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 生产结果详情 -->
    <el-dialog :title="operateTitle" :visible.sync="operatePage" width="800px" append-to-body>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listResult, getResult, delResult, addResult, updateResult } from "@/api/order/result";
import DynamicDetailRenderer from './components/DynamicDetailRenderer.vue';
import { detectDataType, getDataTypeInfo, getPossibleJavaClasses } from './components/dataTypeDetector.js';

export default {
  name: "Result",
  dicts: ['node_test_result','node_result_status','product_line'],
  components: {
    DynamicDetailRenderer
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 节点生产结果表格数据
      resultList: [],
      // 日期范围
      dateRange: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层-操作数据
      operateTitle: "",
      detailOpen: false,
      // 当前生产详情数据
      currentTestDetail: null,
      // 生产到的数据类型
      detectedDataType: 'auto',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nodeId: null,
        sortIndex: null,
        stationCode: null,
        modelCode: null,
        ip: null,
        orderId: null,
        productId: null,
        partNumber: null,
        orderNo: null,
        testDetail: null,
        testResult: null,
        status: null,
        creator: null,
        updater: null,
        deleted: null,
        machineModel: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询节点生产结果列表 */
    getList() {
      this.loading = true;
      listResult(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.resultList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        nodeId: null,
        sortIndex: null,
        stationCode: null,
        ip: null,
        orderId: null,
        productId: null,
        partNumber: null,
        orderNo: null,
        testDetail: null,
        status: null,
        creator: null,
        createTime: null,
        updater: null,
        updateTime: null,
        deleted: null,
        machineModel: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加节点生产结果";
    },
    /** 查看按钮操作 */
    handleOperateView(row) {
      try {
        // 解析testDetail JSON字符串
        this.currentTestDetail = JSON.parse(row.testDetail);

        // 使用新的数据类型生产工具
        this.detectedDataType = detectDataType(this.currentTestDetail);

        // 获取详细的类型信息（用于调试）
        const typeInfo = getDataTypeInfo(this.currentTestDetail);
        const possibleClasses = getPossibleJavaClasses(this.currentTestDetail);

        console.log('生产到的数据类型:', this.detectedDataType);
        console.log('类型详情:', typeInfo);
        console.log('可能的Java类:', possibleClasses);

        // 显示详情对话框
        this.detailOpen = true;
      } catch (error) {
        console.error('解析testDetail失败:', error);
        this.$modal.msgError('生产数据格式错误，无法显示详情');
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除节点生产结果编号为"' + ids + '"的数据项？').then(function() {
        return delResult(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      if (!this.queryParams.stationCode) {
        this.$modal.msgWarning("请先输入站位编码后再导出");
        return;
      }
      if (!this.queryParams.modelCode) {
        this.$modal.msgWarning("请先选择总装线后再导出");
        return;
      }
      this.download('order/result/export', {
        ...this.queryParams
      }, `result_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
